package com.yu.mall.service;

import com.alibaba.fastjson.JSON;
import com.yu.mall.controller.ProductController;
import com.yu.mall.dto.user.UserDTO;
import com.yu.mall.entity.CardVolume;
import com.yu.mall.entity.User;
import com.yu.mall.entity.White;
import com.yu.mall.mapStruct.user.UserChange;
import com.yu.mall.mapStruct.user.UserDTOChange;
import com.yu.mall.mapper.CardVolumeMapper;
import com.yu.mall.mapper.UserMapper;
import com.yu.mall.mapper.WhiteMapper;
import com.yu.mall.util.EmojiFilter;
import com.yu.mall.util.PasswordUtil;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.ResultVO;
import com.yu.mall.vo.user.UserVO;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Objects;

@Service
@Transactional
@Slf4j
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserChange userChange;

    @Autowired
    UserDTOChange userDTOChange;

    @Autowired
    private WhiteMapper whiteMapper;

    @Autowired
    private CardVolumeMapper cardVolumeMapper;

    public ResultVO<UserVO> get(String openid) {
        User user = userMapper.selectByPrimaryKey(openid);
        if(Objects.isNull(user)){
            return ResultUtils.error("用户不存在");
        }
        UserVO userVO = userChange.toVo(user);
        if(StringUtils.isNotBlank(userVO.getPhone())){
            White white = whiteMapper.selectByPrimaryKey(userVO.getPhone());
            if(Objects.nonNull(white)){
                userVO.setIsCard("0");
            }
        }
        return ResultUtils.success(userVO);
    }

    public ResultVO<UserVO> bindUser(HttpServletRequest request,UserDTO userDTO) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        User user = userDTOChange.toBean(userDTO);
        String nickName = user.getNickName();
        if(nickName!=null && !"".equals(nickName)) {
        	if(EmojiFilter.containsEmoji(nickName)) {
        		user.setNickName(EmojiFilter.filterEmoji(nickName));
        		log.info("nickName==="+nickName);
            }
        }
        user.setUpdateTime(new Date());
        int i = userMapper.updateByPrimaryKeySelective(user);
        if(i <= 0){
            return ResultUtils.error("绑定失败");
        }
        user = userMapper.selectByPrimaryKey(user.getOpenid());
        UserVO userVO = userChange.toVo(user);
        String key = userVO.getOpenid() + RandomUtils.nextInt(0,9999);
        String token = PasswordUtil.encode3Des(PasswordUtil.KEY, key);
        HttpSession session = request.getSession();
        session.setAttribute(key, JSON.toJSONString(user));
        session.setMaxInactiveInterval(60*60*24);
        if(StringUtils.isNotBlank(user.getPhone())){
            userVO.setToken(token);
        }
        if(StringUtils.isNotBlank(userVO.getPhone())){
            White white = whiteMapper.selectByPrimaryKey(userVO.getPhone());
            if(Objects.nonNull(white)){
                userVO.setIsCard("0");
            }
        }

        return ResultUtils.success(userVO);
    }

    public ResultVO bindCard(String openid, String card) {
        Example example = new Example(CardVolume.class);
        Criteria createCriteria = example.createCriteria();
        createCriteria.andEqualTo("cardVolumeNum",card);
        createCriteria.andEqualTo("isactivate","0");
        CardVolume cardVolume = cardVolumeMapper.selectOneByExample(example);
        if(Objects.isNull(cardVolume)){
            return ResultUtils.error("卡劵不存在");
        }
        if("0".equals(cardVolume.getIstag())){
            return ResultUtils.error("卡劵失效");
        }

        User user = userMapper.selectByPrimaryKey(openid);
        if(!"".equals(cardVolume.getType()) && cardVolume.getType()!=null) {
        	user.setIsCard(cardVolume.getType());
        }
        
        user.setBalance(user.getBalance().add(new BigDecimal(cardVolume.getAmount())));
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);

        cardVolume.setIstag("0");
        cardVolume.setOpenid(openid);
        cardVolumeMapper.updateByPrimaryKeySelective(cardVolume);
        return ResultUtils.success();
    }
}
